﻿using IService.Managemen;
using Models.Managemen;
using ModelToDto.Managemen;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Managemen
{
    public class RoleService : BaseService, IRoleService
    {
        public ISqlSugarClient _sqlSugarClient;
        public RoleService(ISqlSugarClient sqlSugarClient) : base(sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        public Task<RoleMenuDTO> GetRoleMenue(int roleId)
        {
            // var role=_sqlSugarClient.Queryable<Mp_Role>().Where(c=>c.RoleId==roleId).First();
            //获取角色菜单
            var roleMenu = sqlSugarClient.Queryable<Mp_RoleMenue>().RightJoin<Mp_Role>((o, x) => o.RoleId == x.RoleId).Where(o => o.RoleId == roleId).Select((o, x) => new
            {
                roleId = x.RoleId,
                roleName = x.Text,
                menuId = o.MenuId
            }).ToList();
            ///获取所有菜单
            Expressionable<Mp_Menue> expression = Expressionable.Create<Mp_Menue>();

            var menueTree = sqlSugarClient.Queryable<Mp_Menue>().Where(expression.ToExpression()).ToTree(it => it.ChildList, it => it.ParentId, 0);
            var firstRole = roleMenu.FirstOrDefault();
            RoleMenuDTO roleMenuDTO = new RoleMenuDTO();
            roleMenuDTO.RoleID = firstRole == null ? roleId : firstRole.roleId;
            roleMenuDTO.RoleName = firstRole == null ? null : firstRole.roleName;

            ///获取菜单ID已经保存的
            var roleMenuIDList = roleMenu.Select(c => c.menuId).ToList();
            ///递归菜单
            roleMenuDTO.MenueListItems = RecursionRoleMenu(menueTree, roleMenuIDList);

            return Task.FromResult(roleMenuDTO);

        }

        //递归时注意返回类型和参数类型，和递归的条件
        private List<MenuList> RecursionRoleMenu(List<Mp_Menue> menueTree, List<int> roleMenuIDList)
        {
            List<MenuList> roleMenuDTO = new List<MenuList>();
            //循环父级菜单判断是否选中
            foreach (var frthItem in menueTree)
            {
                MenuList menuList = new MenuList();
                menuList.Meu_Name = frthItem.Meu_Name;
                menuList.Meu_Id = frthItem.Meu_Id;
                if (roleMenuIDList.Contains(frthItem.Meu_Id))
                {

                    menuList.IsCheck = true;
                }
                else
                {

                    menuList.IsCheck = false;
                }

                if (frthItem.ChildList != null && frthItem.ChildList.Count > 0)
                {
                    menuList.ChildList = RecursionRoleMenu(frthItem.ChildList, roleMenuIDList);
                }
                roleMenuDTO.Add(menuList);
            }
            return roleMenuDTO;
        }

        public async Task<int> RolesMenueAdd(int roleId, List<string> roleList)
        {
            List<Mp_RoleMenue> roleMeue = new List<Mp_RoleMenue>();
            foreach (var item in roleList)
            {
                roleMeue.Add(new Mp_RoleMenue
                {
                    MenuId = Convert.ToInt32(item),
                    RoleId = roleId
                });
            }
            try
            {
                sqlSugarClient.Ado.BeginTran();
                await sqlSugarClient.Deleteable<Mp_RoleMenue>().Where(t => t.RoleId == roleId).ExecuteCommandAsync();
                await InsertList(roleMeue);
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {

                return 0;
            }
        }

        public async Task<bool> FindUserRole(int userId, string path)
        {
            var userRolMenu = await sqlSugarClient.Queryable<Mp_UserRole>().LeftJoin<Mp_RoleMenue>((p, q) => p.RoleId == q.RoleId).LeftJoin<Mp_Menue>((p, q, o) => q.MenuId == o.Meu_Id).Where((p, q, o) => p.UserId == userId && o.Meu_Url == path).Select((p, q, o) => new
            {
                o.Meu_Id

            }).FirstAsync();
            if (userRolMenu?.Meu_Id > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
